在前一篇我們聊到 Secret:管理敏感資訊,解決了應用程式在 Kubernetes 中如何安全地存取機密資料。
接下來要進入 持久化儲存 (PersistentVolume, PVC) 的世界之前,先讓我們回到基礎,認識 Volume 的最簡單兩種型態:EmptyDir 與 HostPath。
這篇文章會先帶你了解為什麼需要 Volume,再介紹這兩種 Volume 的特性,最後透過實作範例把它們串起來。
如果你有在容器裡存過檔案,你可能會遇到這個問題:
這就是為什麼需要 Volume —— 它是一個額外的掛載點,可以用來存資料或共享檔案。
常見的 Volume 類型大致可以分成三類:
今天我們專注在前兩者。
特性
使用情境
以下是一個簡單的例子,app 容器會把文字寫到 /cache,而 sidecar 容器則會讀取同一個檔案:
apiVersion: v1
kind: Pod
metadata:
name: emptydir-demo
spec:
containers:
- name: app
image: busybox
command: [ "sh", "-c", "echo 'Hello from app' > /cache/hello.txt && sleep 3600" ]
volumeMounts:
- name: cache-volume
mountPath: /cache
- name: sidecar
image: busybox
command: [ "sh", "-c", "cat /cache/hello.txt; sleep 3600" ]
volumeMounts:
- name: cache-volume
mountPath: /cache
volumes:
- name: cache-volume
emptyDir: {}
這樣一來,兩個容器就能透過同一個 Volume 共享資料。
特性
使用情境
以下例子會把 Pod 的 log 寫到 Node 的 /var/log/hostpath-demo 資料夾裡:
apiVersion: v1
kind: Pod
metadata:
name: hostpath-demo
spec:
containers:
- name: app
image: busybox
command: [ "sh", "-c", "echo 'Log from app' >> /logs/app.log && sleep 3600" ]
volumeMounts:
- name: host-logs
mountPath: /logs
volumes:
- name: host-logs
hostPath:
path: /var/log/hostpath-demo
type: DirectoryOrCreate
實際跑起來後,你會在 Node 上的 /var/log/hostpath-demo/app.log 找到 log 檔。
| 特性 | EmptyDir | HostPath |
|------------|------------|----------------------------|
| 存活範圍 | 隨 Pod 刪除 | 存在於 Node 上 |
| 適用情境 | 暫存、快取 | 偵錯、Node 特定檔案 |
| 安全性 | 相對安全 | 風險較高(直接接觸 Node 檔案系統) |
| 生產環境建議 | ✅ 可用 | ❌ 謹慎使用 |
最後來一個結合的範例:
YAML 範例
apiVersion: v1
kind: Pod
metadata:
name: volume-mix-demo
spec:
containers:
- name: app
image: busybox
command: [ "sh", "-c", "while true; do echo $(date) >> /cache/app.log; sleep 5; done" ]
volumeMounts:
- name: cache-volume
mountPath: /cache
- name: logger
image: busybox
command: [ "sh", "-c", "tail -f /cache/app.log >> /logs/persisted.log" ]
volumeMounts:
- name: cache-volume
mountPath: /cache
- name: host-logs
mountPath: /logs
volumes:
- name: cache-volume
emptyDir: {}
- name: host-logs
hostPath:
path: /var/log/volume-mix
type: DirectoryOrCreate
這樣就能同時體驗 EmptyDir 的容器間共享,以及 HostPath 的 Node 持久化效果。